﻿#搜索所有包含print(的文件,并在下面那行加入需要加入的字符串
#主要用于添加日志上报的脚本修改
#1.读取指定文件夹下的所有文件

import os,re

def readFileAndInsert(filename):
	desLine = []
	with open(filename, 'r') as f:
		lines = f.readlines()
		index = 0 
		count = len(lines)	
		while index<count:
			desLine.append(lines[index])
			if lines[index].__contains__("print("):
				spaceStr = re.match(r"^(\s*)print\(",lines[index]) 
				temp = lines[index].replace('print(','writeInfo(')
				temp = "if writeInfo then\n" + temp 
				if spaceStr:
					temp = spaceStr.group(1) + temp
				if index+1 == count :
					temp = '\n' + temp
				if spaceStr:
					temp = temp + spaceStr.group(1) + 'end\n'
				else:
					temp = temp + 'end\n'
				desLine.append(temp)
			index = index + 1
	print("change",desLine)
	with open(filename, 'w') as f:
		f.writelines(desLine)
	
def readFileAndChange(filename):
	print('filename',filename)
	lines = ''
	with open(filename, 'r+') as f:
		lines = f.readlines()
	count = len(lines)
	print('count',count)
	while count>0:
		str = lines[count-1]
		desStr = ')\n'
		orgStr = ''
		if re.match(r"^(\s*)writeInfo\(",str):
			print("str-->",str)
			groups = str.split(',') 
			glen = len(groups)
			print("glen-->",glen)
			while glen>1:	
				gr = re.sub('\\).*$','',groups[glen-1])
				print("gr",gr)
				print("gr[1]",gr)
				tempstr = "table.concat("+gr.strip()+' , \":\")'
				print("tempstr",tempstr)
				if glen==len(groups):
					orgStr = groups[glen-1] + orgStr ;
					desStr =  tempstr + desStr
				else:
					orgStr = groups[glen-1] +',' + orgStr ;
					desStr =  tempstr+","+ desStr
				glen = glen -1 
			print("desStr",desStr)
			if len(groups)>1:
				lines[count-1] = lines[count-1].replace(orgStr,desStr)
		count = count - 1
	with open(filename, 'w') as f:
		f.writelines(lines)




def replaceFiles(filePath):
	pathDir = os.listdir(filePath)
	for allDir in pathDir:
		child = os.path.join('%s%s' %(filePath,allDir))
		if os.path.isdir(child): 
			child = os.path.join('%s%s/' %(filePath,allDir))
			replaceFiles(child)
		else:
			readFileAndInsert(child)

def changeFiles(filePath):
	pathDir = os.listdir(filePath)
	for allDir in pathDir:
		child = os.path.join('%s%s' %(filePath,allDir))
		if os.path.isdir(child):
			child = os.path.join('%s%s/' %(filePath,allDir)) 
			changeFiles(child)
		else:
			readFileAndChange(child)

#changeFiles("C:/Users/Administrator/Desktop/test/")		
#changeFiles("D:/project/mjcg-client/src/app/part/lyc/")
#replaceFiles("C:/Users/Administrator/Desktop/test/")
#replaceFiles("D:/NewProject/mjcg-client/src/app/part/lyc/")
#replaceFiles("D:/project/mjcg-client/src/app/part/lyc/")
